<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
class WeixinController extends HomeController {

	public $appid = 'wx66288ac7b2e12558';
	public $appsecret = "12858b99ec84e380e652c212b1b76ad4";	
	public function index(){
		//获得参数 signature nonce token timestamp echostr
		$nonce     = $_GET['nonce'];
		$token     = 'yewu';
		$timestamp = $_GET['timestamp'];
		$echostr   = $_GET['echostr'];
		$signature = $_GET['signature'];
		//形成数组，然后按字典序排序
		$array = array();
		$array = array($nonce, $timestamp, $token);
		sort($array,SORT_STRING);
		//拼接成字符串,sha1加密 ，然后与signature进行校验
		$str = sha1( implode( $array ) );
		if( $str  == $signature && $echostr ){
			//第一次接入weixin api接口的时候
			echo  $echostr;
			exit;
		}else{
			$this->reponseMsg();
		}				
	}
	public function reponseMsg(){
		$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
		//simplexml_load_string 是把XML转换成字符串
		$postObj = simplexml_load_string( $postArr );
		/*<xml>
		<ToUserName><![CDATA[toUser]]></ToUserName>
		<FromUserName><![CDATA[FromUser]]></FromUserName>
		<CreateTime>123456789</CreateTime>
		<MsgType><![CDATA[event]]></MsgType>
		<Event><![CDATA[subscribe]]></Event>
		</xml>*/
		//strtolower是把所有字符转换成小写
		if(strtolower($postObj->MsgType) == 'event'){
			//用户关注
			if(strtolower($postObj->Event) == 'subscribe'){
				//回复用户消息(纯文本格式)	
				//发送者ID
				$toUser   = $postObj->FromUserName;
				//公众号ID
				$fromUser = $postObj->ToUserName;
				$time     = time();
				$msgType  = 'text';
				//获取用户信息插入数据库
				$res = $this->addopenid($toUser);
				$content  = '插入数据'.$res;
				$template = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
				$info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
				echo $info;		

			}
			//用户取消
			if(strtolower($postObj->Event) == 'unsubscribe'){
				
				//发送者ID
				$toUser   = $postObj->FromUserName;
				//公众号ID
				$fromUser = $postObj->ToUserName;
				$time     = time();
				$msgType  = 'text';
				//删除数据库中的用户记录
				$res = $this->delopenid($toUser);
				$content  = '删除成功'.$res;
				$template = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
				$info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
				echo $info;		
			}
		}
		//判断用户发送的消息
		if(strtolower($postObj->MsgType) == 'text'){
		 	//if(strtolower($postObj->Content) == '你好'){
				switch ($postObj->Content) {
					case '你好':
						$content  = $postObj->FromUserName;
						break;
					
					case '不好':
						$content  = '不好';
						break;
				}

				$toUser   = $postObj->FromUserName;
				$fromUser = $postObj->ToUserName;
				$time     = time();
				//$content  = '欢迎关注我们的微信公众账号';
				$msgType  =  'text';
				$template = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
				$info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
				echo $info;

				$template  = "<xml>
							<ToUserName><![CDATA[toUser]]></ToUserName>
							<FromUserName><![CDATA[fromUser]]></FromUserName>
							<CreateTime>12345678</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>1</ArticleCount>
							<Articles>";					
				$template  .="</Articles>
							</xml>";

		}

	}
	public function getWxAccess_Token(){
		$appid     = $this->appid;   
		$appsecret = $this->appsecret;
		$url       = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret."";

		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER,1);
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}

		$arr = json_decode($res,true);
		$value = $arr['access_token'];
		S('wxaccess_Token',$value,array('type'=>'file','expire'=>7000));
	}
	public function getcallbackip(){
		$access_token = S('name');
		$url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token."";

		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ($ch,CURLOPT_RETURNTRANSFER,1);
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		echo "<per>";
		var_dump($arr);
		echo "</per>";

	}
	//客服系统主动发送消息
	public function bb(){
		$access_token = "teRVLghO1WVvV4eplp-tOpNXmwl0j4Z3uBtgLDjcDGharBc8y25HCzMOgaXnrBv5HaSMjGEZSslGwSKeb5ilfirVbGRoKpRKO__GvsCBJvkJUOgAGAYJD";
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
		$data = '{
				    "touser":"oaPkKxNEfpKn4ByVXFcwbEt-2BgE",
				    "msgtype":"text",
				    "text":
				    {
				         "content":"Hello World"
				    }
				}';

		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		echo "<per>";
		var_dump($arr);
		echo "</per>";

	}
	//报表发送(门市提醒)
	public function mb($touser = '',$template_id = '',$url='',$xsjd = '',$ddbh= '',$name = '',$phone = '',$qq = '',$qd = '',$lb = '',$kf = '',$bz = '',$cztime = ''){
		if(!S('wxaccess_Token')){
			$this->getWxAccess_Token();
		}
		$access_token = S('wxaccess_Token');
		
		$shuju = "{

    		\"touser\":\"$touser\",

    		\"template_id\":\"$template_id\",
			\"url\":\"$url\",

    		\"topcolor\":\"#FF0000\",

			    \"data\":{

			            \"jd\": {

			                \"value\":\"$xsjd\",

			                \"color\":\"#666666\"

			            },

			            \"ddbh\":{

			                \"value\":\"$ddbh\",

			                \"color\":\"#173177\"

			            },

			            \"name\": {

			                \"value\":\"$name\",

			                \"color\":\"#AA0000\"

			            },

			            \"phone\":{

			                \"value\":\"$phone\",

			                \"color\":\"#AA0000\"

			            },

			            \"qq\":{

			                \"value\":\"$qq\",

			                \"color\":\"#AA0000\"

			            },

			            \"qd\":{

			                \"value\":\"$qd\",

			                \"color\":\"#173177\"

			            },

			            \"lb\":{

			                \"value\":\"$lb\",

			                \"color\":\"#173177\"

			            },

			            \"kf\":{

			                \"value\":\"$kf\",

			                \"color\":\"#173177\"

			            },
			            
			            \"xsjd\":{

			                \"value\":\"$xsjd\",

			                \"color\":\"#173177\"

			            },

			            \"fs\":{

			                \"value\":\"$cztime\",

			                \"color\":\"#173177\"

			            },

			            \"bz\":{

			                \"value\":\"$bz\",

			                \"color\":\"#173177\"

			            },
			            \"zt\":{

			                \"value\":\"$ywzt\",

			                \"color\":\"#173177\"

			            }


			    }

			}";
		
		if($access_token){
			$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token."";
		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $shuju);
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);

		return $arr;

		}


	}
	//成交信息提醒（提醒5人，线上门市、线上经理、线下经理、店长、老板）
	public function cjtx($touser = '',$template_id = '',$url='',$djcj = '',$ddbh= '',$ddtime = '',$xsjd = '',$xxjd = '',$lb = '',$money = '',$zfkx = '',$zffs = '',$zt = '',$pd = '',$qd = '',$bz = ''){
		if(!S('wxaccess_Token')){
			$this->getWxAccess_Token();
		}
		$access_token = S('wxaccess_Token');
		
		$shuju = "{

    		\"touser\":\"$touser\",

    		\"template_id\":\"$template_id\",
			\"url\":\"$url\",

    		\"topcolor\":\"#FF0000\",

			    \"data\":{

			            \"djcj\": {

			                \"value\":\"$djcj\",

			                \"color\":\"#666666\"

			            },

			            \"ddbh\":{

			                \"value\":\"$ddbh\",

			                \"color\":\"#173177\"

			            },

			            \"cjtime\": {

			                \"value\":\"$ddtime\",

			                \"color\":\"#AA0000\"

			            },

			            \"xsjd\":{

			                \"value\":\"$xsjd\",

			                \"color\":\"#AA0000\"

			            },
						\"xxjd\":{

			                \"value\":\"$xxjd\",

			                \"color\":\"#AA0000\"

			            },

			            \"ywlb\":{

			                \"value\":\"$lb\",

			                \"color\":\"#AA0000\"

			            },

			            \"money\":{

			                \"value\":\"$money\",

			                \"color\":\"#173177\"

			            },

			            \"lb\":{

			                \"value\":\"$lb\",

			                \"color\":\"#173177\"

			            },

			            \"cjlx\":{

			                \"value\":\"$zfkx\",

			                \"color\":\"#173177\"

			            },
			            
			            \"zffs\":{

			                \"value\":\"$zffs\",

			                \"color\":\"#173177\"

			            },
						\"zt\":{

			                \"value\":\"$zt\",

			                \"color\":\"#173177\"

			            },

			            \"pd\":{

			                \"value\":\"$pd\",

			                \"color\":\"#173177\"

			            },

			            \"qd\":{

			                \"value\":\"$qd\",

			                \"color\":\"#173177\"

			            },
			            \"bz\":{

			                \"value\":\"$bz\",

			                \"color\":\"#173177\"

			            }


			    }

			}";
		
		if($access_token){
			$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token."";
		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $shuju);
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);

		return $arr;

		}


	}
	//获取用户信息
	public function addopenid($openid){
		if(!S('wxaccess_Token')){
			$this->getWxAccess_Token();
		}
		$access_token = S('wxaccess_Token');
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		$res = curl_exec($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		$arr['update_time'] = time();
		$res = D('Weixin')->add($arr);
		return $res;
	}
	//删除用户
	public function delopenid($toUser){
		$res = D('Weixin')->where("openid='%s'",array($toUser))->delete();
		return $res;
		var_dump($res);
	}	
	//获取微信关注用户信息
	public function yhxx(){
		if(!S('wxaccess_Token')){
			$this->getWxAccess_Token();
		}
		$access_token = S('wxaccess_Token');
		$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."";
		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		$res = curl_exec($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		

		foreach ($arr as $key => $value) {
			foreach ($value['openid'] as $key => $value) {
				$openid[] = array('openid'=>$value,'lang'=>"zh-CN");
				}
		}
	    $jsonopenid = json_encode($openid);
		$data ="{\"user_list\":$jsonopenid
				};";

		$url1 = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=".$access_token."";
		curl_setopt ($ch,CURLOPT_URL,$url1);
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data);
		$res1 = curl_exec($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr1 = json_decode($res1,true);
		var_dump($arr1);
		$weixin = M("weixin");

		foreach ($arr1['user_info_list'] as $key => $v) {


				if(!$weixin->where(array('openid'=>array('eq',$v['openid'])))->find()){
				$v['update_time'] = time();
				$res = $weixin->add($v);
				}else{
					$res = false;
				}
				var_dump($res);

		}
	}
	//获取网页access_token、refresh_token
	public function wyaccess_token($code){
		$appid        = 'wx66288ac7b2e12558';
		//$code         = $code;
		$appsecret    = '12858b99ec84e380e652c212b1b76ad4';
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		// S('wyaccess_Token',$arr['access_token'],array('type'=>'file','expire'=>7000));
		// if(!S('wyrefresh_token',$arr['refresh_token'])){
		//     S('wyrefresh_token',$arr['refresh_token']);
		// }
		// if(!S('code',$code)){
		// 	S('code',$code);
		// }
		return $arr;
		
	}

	//更新网页access_token
	public function getwyaccess_token(){
		$appid         = 'wx66288ac7b2e12558';
		$code          =  S('code');
		$refresh_token =  S('wyrefresh_token');
		$url          = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token'.'&refresh_token='.$refresh_token;
		$ch = curl_init();
		curl_setopt ($ch,CURLOPT_URL,$url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		var_dump($arr);
	}
}